package com.bolt.support.freemarker;

import com.bolt.common.io.IoUtil;
import com.bolt.convention.exception.ServiceException;

import java.io.OutputStream;
import java.io.Writer;
import java.util.Map;

/**
 * Created by Administrator on 2020/10/13.
 */
public class FreeMarkerTemplate extends AbstractTemplate {

    freemarker.template.Template rawTemplate;

    /**
     * 包装Freemarker模板
     *
     * @param beetlTemplate Beetl的模板对象 {@link freemarker.template.Template}
     * @return {@link FreeMarkerTemplate}
     */
    public static FreeMarkerTemplate wrap(freemarker.template.Template beetlTemplate) {
        return (null == beetlTemplate) ? null : new FreeMarkerTemplate(beetlTemplate);
    }

    /**
     * 构造
     *
     * @param freemarkerTemplate Beetl的模板对象 {@link freemarker.template.Template}
     */
    public FreeMarkerTemplate(freemarker.template.Template freemarkerTemplate) {
        this.rawTemplate = freemarkerTemplate;
    }

    @Override
    public void render(Map<?, ?> bindingMap, Writer writer) {
        try {
            rawTemplate.process(bindingMap, writer);
        } catch (Exception ex) {
           throw new ServiceException(ex);
        }
    }

    @Override
    public void render(Map<?, ?> bindingMap, OutputStream out) {
        render(bindingMap, IoUtil.getWriter(out, this.rawTemplate.getEncoding()));
    }
}

 